<template>
	<view>
		<view class="header-info">
			<view>
				<text>输入格式:</text>
				<text>[{"question": "", "answer": ""}]</text>
			</view>
			<button type="default" size="mini" @click="copy">复制</button>
		</view>
		<linke-ux-editor v-model="content" :cloud="false" :url="url"></linke-ux-editor>
		<button type="primary" style="margin: 0 10px;" @click="save">保存</button>
	</view>
</template>

<script>
	import uxEditor from '../../uni_modules/linke-ux-editor/static/js/editor.js';
	import uniCopy from '../../lib/js_sdk/xb-copy/uni-copy.js'
	export default {
		data() {
			return {
				content: [],
				// 上传文件的URL，如 'https://a.com/oss/upload',
				// 返回数据 { data: '文件地址'}，注意格式一定要正确
				url: '',
				// 是否启用 uniCloud上传，url 二选一，详细看文档说明
				cloud: false
			};
		},
		props: {},
		methods: {
			copy() {
				uniCopy({
					content: '[{"question": "", "answer": ""}]',
					success: (res) => {
						uni.showToast({
							title: res,
							icon: 'none'
						})
					},
					error: (e) => {
						uni.showToast({
							title: e,
							icon: 'none',
							duration: 3000,
						})
					}
				})
			},
			save() {
				try {
					let content = JSON.parse(this.content[0].txtContent)
					console.log(content)
					const flag = content.every(v => {
						return v.question != '' && v.answer != ""
					})
					if (flag) {
						let value = uni.getStorageSync('topicList') || '[]'
						value = JSON.parse(value)
						value = [...value, ...content]
						value = value.map(v => {
							return {
								question: v.question,
								answer: v.answer
							}
						})
						console.log(value, JSON.stringify(value))
						uni.setStorageSync('topicList', JSON.stringify(value));
						uni.showToast({
							title: '导入成功',
							mask: true,
							duration: 1000
						})
					} else {
						uni.showToast({
							title: '请检查输入字段及内容',
							icon: 'none',
							mask: true,
							duration: 1500
						})
					}
				} catch (e) {
					console.log(e)
					uni.showToast({
						title: '输入格式不正确',
						icon: 'none',
						mask: true,
						duration: 1500
					});
				}
			},
		},
		onShow() {
			uxEditor.tempDataHandler(this.content);
		}
	};
</script>

<style lang="scss">
	.header-info {
		margin: 20rpx;
		color: #ddd;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.opt-box {
		display: none;
	}
</style>
